$(function(){
    var formFlag=false;
    //初始化form表单
    var form = $("#form_add_update_user").Validform({
        tiptype:2, //可选项 1=>pop box,2=>side tip(parent.next.find; with default pop),3=>side tip(siblings; with default pop),4=>side tip(siblings; none pop)，默认为1，也可以传入一个function函数，自定义提示信息的显示方式（可以实现你想要的任何效果，具体参见demo页）;
        ignoreHidden:false,//可选项 true | false 默认为false，当为true时对:hidden的表单元素将不做验证;
        tipSweep:false,//可选项 true | false 默认为false，只在表单提交时触发检测，blur事件将不会触发检测（实时验证会在后台进行，不会显示检测结果）;
        showAllError:false,//可选项 true | false，true：提交表单时所有错误提示信息都会显示，false：一碰到验证不通过的就停止检测后面的元素，只显示该元素的错误信息;
        postonce:true, //可选项 表单是否只能提交一次，true开启，不填则默认关闭;
        ajaxPost:true, //使用ajax方式提交表单数据，默认false，提交地址就是action指定地址;
        usePlugin:{
            passwordstrength:{}
        },
        datatype:{
            //根据业务不同定义特殊的正则校验
            "orgcard_idcard":function(gets,obj,curform,regxp){
                var reg,
                    errmsg;
                var cardType=curform.find("#cardType").val();
                if(cardType==undefined || cardType==null || cardType==""){
                    return "请选择证件类型";
                }
                if("1"==cardType){
                    reg = regxp["idcard"];
                    errmsg= $.Tipmsg.w.idcard;
                }else if("2"==cardType){
                    reg=regxp["orgcard"];
                    errmsg = $.Tipmsg.w.orgcard;
                }
                if(reg.test(gets)){
                    return true;
                }else{
                    return errmsg;
                }
            }
        },
        beforeSubmit:function(curform){
        },
        callback:function(data){
            if(data.status=="T"){
                window.location.href=window.location.href;
            }else{
                form.resetStatus();
            }
        }
    });
    //初始化需要校验的内容
    form.addRule([
        {
            ele:"#username",
            datatype:"username"
        },
        {
            ele : "#password",
            datatype : "pwd"
        },
        {
            ele:"#realname",
            datatype:"realname"
        },
        {
            ele:"#re_password",
            datatype:"pwd"
        },
        {
            ele:"#cardType",
            datatype:"*"
        },
        {
            ele:"#certiCard",
            datatype:"orgcard_idcard"
        },
        {
            ele:"#phone",
            datatype:"m"
        },
        {
            ele:"#email",
            datatype:"e"
        }
    ]);

    /**
     * 新增用户按钮
     */
    $("#addNewUser_btn,a[name=upd_user_btn]").click(function(){
        var id = $(this).data("id");
        if(id != undefined){
            $.ajax({
                url:htx+"/user/userInfo",
                data:{userId:id},
                type:"POST",
                dataType:"JSON",
                success:function(data){
                    if(data.status=="T"){
                        var info = data.info;
                        $.each(info,function(key){
                            $("#add_user_div").find("[name="+key+"]").val(info[key]);
                        });
                    }
                }
            });
        }
        form.resetForm();
        admin.dialog_show("新增用户","#myModal","#add_user_div",600,400);
    });

    /**
     * 用户授权按钮
     */
    $("a[name=user_auth_btn]").click(function(){
        var userid = $(this).data("id");
        admin.dialog_show("用户授权","#myModal","#auth_div",400,400);
        $("#auth_div #userId").val(userid);
        $('#auth-role').trigger('click');
    });

    /**
     * 显示用户详情
     */
    $("a[name=show_info_btn]").click(function(){
        var id = $(this).data("id");
        var param = {userId:id};
        $.ajax({
            url:htx+"/user/userInfo",
            data:{userId:id},
            type:"POST",
            dataType:"JSON",
            success:function(data){
                if(data.status=="T"){
                    var info = data.info;
                    $.each(info,function(key){
                        $("#show_user_info").find("[name="+key+"]").html(info[key]);
                    });
                }
            }
        });
        admin.dialog_show("用户详细信息","#myModal","#show_user_info",400,400);
    });

    /**
     *  角色树
     */
    $("#auth-role").click(function(){
        //初始化树
        var zNodes =new Array();
        $.ajax({
            url:htx+"/role/getRoleList",
            type:"POST",
            async: false,
            dataType:"JSON",
            success:function(data){
                for(var i=0;i<data.length;i++) {
                    var json = {id:data[i].id,pId:data[i].parentRoleId,name:data[i].roleName};
                    zNodes.push(json);
                }
            }
        });
        showZtree(zNodes);
        //反显此资源配置的角色树
        var userid = $("#auth_div #userId").val();
        $.ajax({
            url:htx+"/user/selectUserRoleAuth",
            type:"POST",
            data:{userId:userid},
            async: false,
            dataType:"JSON",
            success:function(data){
                if(data.status=="T"){
                    var info =data.info;
                    for (var i = 0; i < info.length; i++) {
                        var zTree = $.fn.zTree.getZTreeObj("auth-tree");
                        var nodes = zTree.getNodesByParam("id", info[i].roleId, null);
                        zTree.checkNode(nodes[0], true, false);
                    }
                }
            }
        });
    });

    /**
     * 菜单树
     */
    $("#auth-menu").click(function(){
        //初始化树
        var zNodes =new Array();
        $.ajax({
            url:htx+"/menu/getMenuToJSON",
            async: false,
            dataType:"JSON",
            success:function(data){
                if(data.status=="T"){
                    var info = data.info;
                    for(var i=0;i<info.length;i++) {
                        var json = {id:info[i].id,pId:info[i].parentMenuId,name:info[i].cname};
                        zNodes.push(json);
                    }
                }
            }
        });
        showZtree(zNodes);
        var checkNodes="";
        var userid = $("#auth_div #userId").val();
        //反显此资源配置的角色树
        $.ajax({
            url:htx+"/user/selectUserMenuAuth",
            type:"POST",
            async:false,
            data:{userId:userid},
            dataType:"JSON",
            success:function(data){
                if(data.status=="T"){
                    checkNodes=data.info;
                }
                var zTree = $.fn.zTree.getZTreeObj("auth-tree");
                if (checkNodes != undefined && checkNodes != null && checkNodes != "") {
                    for (var i = 0; i < checkNodes.length; i++) {
                        var nodes = zTree.getNodesByParam("id", checkNodes[i].menuId, null);
                        zTree.checkNode(nodes[0], true, false);
                    }
                }
            }
        });
    });
    function showZtree(zNodes) {
        //初始化菜单树参数
        var setting = {
            view: {
                dblClickExpand: true,
                showLine: false,
                selectedMulti: false,
                showIcon: true
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                }
            },
            check: {
                enable: true,
                chkStyle: "checkbox",
                chkboxType: {"Y": "ps", "N": "ps"}
            }
        };
        admin.show_ztree(zNodes, "auth-tree", true,false, setting);
    }

    /**
     * 保存授权按钮
     */
    $("#save_auth_btn").click(function(){
        var zTree = $.fn.zTree.getZTreeObj("auth-tree");
        var checkNodes=zTree.getCheckedNodes(true);
        var authType = $("#auth_div input[name=authType]:checked").val();
        var checkId = new Array();

        for(var i=0;i<checkNodes.length;i++){
            checkId.push(checkNodes[i].id);
        }
        var userid=$("#auth_div #userId").val();
        layer.confirm(
          "确定保存权限信息",
            {btn:["确定","取消"]},
            function(){
                $.ajax({
                    url:htx+"/user/saveUserAuth",
                    type:"POST",
                    data:{checkId:checkId,userId:userid,authType:authType},
                    traditional:true,
                    async:false,
                    dataType:"JSON",
                    success:function(data){
                        if(data.status=="T"){
                            layer.msg("授权成功",{time:800},function(){
                                window.location.reload();
                            })
                        }else{
                            layer.msg(data.info);
                        }
                    }
                });
            },
            function(){

            }
        );
    });

    /**
     * 激活用户
     */
    $("a[name=activate_btn]").click(function(){
        var _this = $(this);
        layer.confirm(
            "确定要激活此用户",
            {
                btn:["确定","取消"],
                title:"提示"
            },
            function(){
                var userid = _this.data("id");
                $.ajax({
                    url:htx+"/user/userActivate",
                    type:"POST",
                    data:{userId:userid},
                    async:false,
                    dataType:"JSON",
                    success:function(data){
                        if(data.status=="T"){
                            layer.msg(data.info,{time:800},function(){
                                window.location.reload();
                            })
                        }else{
                            layer.msg(data.info);
                        }
                    }
                });
            }
        );
    });

    /**
     * 冻结用户
     */
    $("a[name=frozen_btn]").click(function(){
        var _this = $(this);
        layer.confirm(
            "确定要取消激活此用户",
            {
                btn:["确定","取消"],
                title:"提示"
            },
            function(){
                var userid = _this.data("id");
                $.ajax({
                    url:htx+"/user/userFrozen",
                    type:"POST",
                    data:{userId:userid},
                    traditional:true,
                    async:false,
                    dataType:"JSON",
                    success:function(data){
                        if(data.status=="T"){
                            layer.msg(data.info,{time:800},function(){
                                window.location.reload();
                            });

                        }else{
                            layer.msg(data.info);
                        }
                    }
                });
            }
        );
    });

    /**
     * 删除用户
     */
    $("a[name=user_delete_btn]").click(function(){
        var _this = $(this);
        layer.confirm(
            "确定要删除此用户",
            {
                btn:["确定","取消"]
            },
            function(){
                var userid = _this.data("id");
                $.ajax({
                    url:htx+"/user/userDelete",
                    type:"POST",
                    data:{userId:userid},
                    traditional:true,
                    async:false,
                    dataType:"JSON",
                    success:function(data){
                        if(data.status=="T"){
                            layer.msg(data.info,{time:800},function(){
                                window.location.reload();
                            })
                        }else{
                            layer.msg(data.info);
                        }
                    }
                });
            }
        );
    });

    $("#refreshUserAuth_btn").click(function(){
        layer.confirm(
            "确定要刷新所有用户的权限",
            {
                btn:["确定","取消"]
            },
            function(){
                $.ajax({
                    url:htx+"/user/refreshAllUserAuth",
                    type:"POST",
                    dataType:"JSON",
                    success:function(data){
                        if(data.status=="T"){
                            layer.msg(data.info);
                        }else{
                            layer.msg(data.info,{time:800},function(){
                            });
                        }
                    }
                });
            }
        );
    });
});